import { defineStore } from 'pinia'
import store2 from 'store2'
import _ from 'lodash'

// 数组元素的类型
type Item = {
  id: string,
  screenshot: string,
  title: string,
  url: string,
  href: string
}

type WebsiteState = {
  list: Item[]
}

export const useWebsiteStore = defineStore({
  id: 'websites',

  state: (): WebsiteState => ({
    list: []
  }),

  actions: {
    add (item: Item) {
      this.list.unshift(item)
      store2.set('websites', this.list)
    },

    init () {
      this.list = store2.get('websites') || []
    },

    deleteItem (id: string) {
      const filterList = this.list.filter((li) => li.id !== id)
      this.list = filterList
      store2.set('websites', this.list)
    }
  },

  getters: {
    isSave() {
      return (item: Item): Item | undefined => {
        return this.list.find((li) => li.href === item.href)
      }
    },

    find () {
      return (keywords: string) => {
        if (keywords !== '') {
          let result = _.filter(this.list, (item: Item) => {
            let partten = new RegExp(keywords, 'i')
            return partten.test(item.title)
          })
          return result
        } else {
          return this.list
        }
      }
    }
  }
})